package com.android.manghe.cart.fragment

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.view.MVPFragment
import com.android.base.tools.ToastUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.cart.presenter.PCartTab
import com.android.manghe.config.events.RefreshCartEvent
import com.android.manghe.market.adapter.CartPageAdapter
import com.android.manghe.market.adapter.multi.CartGoodLevel
import com.android.manghe.market.adapter.multi.CartRecommendLevel
import com.android.manghe.market.model.CartGoodListRes
import com.android.manghe.mine.model.MemberIndexRes
import com.android.manghe.orderpay.activity.MarketOrderPayFromCartActivity
import com.android.manghe.orderpay.activity.NoPriceMarketOrderPayFromCartActivity
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.eightbitlab.rxbus.Bus
import com.eightbitlab.rxbus.registerInBus
import kotlinx.android.synthetic.main.activity_cart.*
import java.text.DecimalFormat

class CartTabFragment : MVPFragment<PCartTab>() {

    private var adapter: CartPageAdapter? = null
    private var isEdit = false

    override fun getLayoutId(): Int {
        return R.layout.activity_cart
    }

    override fun initData(savedInstanceState: Bundle?, parent: View?) {
        titleBar.setToolbar("购物车")
            .setTitleAndStatusBgColor(R.color.white)
            .setRightText("编辑") {
                if (!p.goodList.isNullOrEmpty()) {
                    isEdit = !isEdit
                    adapter?.setEditMode(isEdit)
                    layoutBottomBar.visibility = if (isEdit) View.GONE else View.VISIBLE
                    titleBar.setRightText(if (isEdit) "完成" else "编辑")
                }
            }

        Bus.observe<RefreshCartEvent>().subscribe {
            p.loadCardGoodData(false)
        }.registerInBus(this)
        val itemEntityList = java.util.ArrayList<MultiItemEntity>()
        itemEntityList.add(CartGoodLevel(p.goodList))
        itemEntityList.add(CartRecommendLevel(arrayListOf()))
        recyclerView.layoutManager = LinearLayoutManager(activity)
        adapter = CartPageAdapter(activity, itemEntityList)
        recyclerView.adapter = adapter
        adapter!!.setListener(object : CartPageAdapter.IModifyCallBack {
            override fun onModified(
                selectedGoodList: MutableList<CartGoodListRes.DataBean.CartGoodsBean>?,
                totalPrice: Double
            ) {
                val format = DecimalFormat("0.00")
                tvTotalPrice.text = "￥${format.format(totalPrice)}"
            }

            override fun modifyGoodNum(
                goodId: String?,
                num: Int,
                spec: String?,
                isSelected: Boolean
            ) {
                p.modifyCardGood(goodId, spec, num, isSelected)
            }

            override fun onDelete(id: String?) {
                p.deleteCartGood(id)
            }

        })

        tvOriginalBuy.setOnClickListener {
            if (p.goodList.isEmpty()) {
                ToastUtil.showLong(activity, "购物车中无商品可结算哦")
                return@setOnClickListener
            }
            adapter?.let {
                val selectedGoodList = it.selectedCartGoodList
                if (selectedGoodList.size == 0) {
                    ToastUtil.showLong(activity, "请勾选您要结算的商品")
                    return@setOnClickListener
                }
                open(
                    MarketOrderPayFromCartActivity::class.java, hashMapOf<String, Any>(
                        "selectedGoodList" to selectedGoodList,
                        "flowUserScore" to p.flowUserScore,
                        "isMember" to p.isMember
                    )
                )
            }

        }
        ivCheckAll.setOnClickListener {
            //全选
            if (!p.goodList.isNullOrEmpty()) {
                adapter?.let {
                    val isSelected = it.toggleSelectedAll()
                    ivCheckAll.setImageResource(if (isSelected) R.mipmap.tick_click else R.mipmap.icon_tick_default)
                }
            }
        }
        tvCanUse.setOnClickListener {
            if (p.goodList.isEmpty()) {
                ToastUtil.showLong(activity, "购物车中无商品可结算哦")
                return@setOnClickListener
            }
            adapter?.let {
                val selectedGoodList = it.selectedCartGoodList
                if (selectedGoodList.size == 0) {
                    ToastUtil.showLong(activity, "请勾选您要结算的商品")
                    return@setOnClickListener
                }
                open(
                    NoPriceMarketOrderPayFromCartActivity::class.java, hashMapOf<String, Any>(
                        "selectedGoodList" to selectedGoodList
                    )
                )
            }
        }
        if(UserHolder.getUserInfo(activity) != null) {
            p.loadCardGoodData(true)
            p.loadRecommendGoods()
        }
    }

    override fun onResume() {
        super.onResume()
        if(UserHolder.getUserInfo(activity) != null) {
            getMemberInfo()
        }
    }

    private fun getMemberInfo() {
        val userInfo = UserHolder.getUserInfo(activity?.applicationContext)
        if (userInfo != null) {
            p.getMemberInfo(userInfo!!.UID, userInfo!!.TOKEN)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Bus.unregister(this)
    }

    fun updateCartGoods() {
        adapter?.let {
            it.setData(0, CartGoodLevel(p.goodList))
        }
    }

    fun updateRecommendGoods() {
        adapter?.let {
            it.setData(1, CartRecommendLevel(p.recommendGoodList))
        }
    }

    /**
     * 更新会员相关控件
     */
    fun updateMemberInfo(memberIndexBean: MemberIndexRes.DataBean) {
        tvCanUse.text =
            "可用余额${if (memberIndexBean.member.exemptAmount == null) 0 else memberIndexBean.member.exemptAmount}元"
    }

}